<template>
    <section class="wrapper" @click.stop = "hideDialog()">
        <div id="operation">
            <div class="top-edit">
                <el-button size="small" @click="addDepartment" icon="el-icon-plus">添加</el-button>
                <el-button size="small" @click="reFresh"><i class="fa fa-refresh"></i> 刷新</el-button>
            </div>
        </div>
        <el-tree :data="defaultData"  :render-content="renderOldContent" class="el_tree1"></el-tree>
        <el-tree
                :data="treeList"
                :props="defaultProps"
                node-key="id"
                accordion
                @node-click="nodeclick"
                :default-expanded-keys="array"
                :render-content="renderContent">
        </el-tree>

        <!--详情dialog框-->
        <el-dialog @close="()=>{this.detailVisible = false}" title="详情" :visible.sync="detailVisible">
            <div :model="editForm" class="dialog-company-detail">
                <el-row>
                    <el-col :span="6" class="dialog-comData-name">部门名称：</el-col>
                    <el-col :span="18" >{{editForm.editValue}}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="dialog-comData-name">上级部门：</el-col>
                    <el-col :span="18" >{{parentName.parentName}}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="dialog-comData-name">管理者：</el-col>
                    <el-col :span="18" >{{leaderNewValue}}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="dialog-comData-name">描述：</el-col>
                    <el-col :span="18" >{{editForm.editDes}}</el-col>
                </el-row>
                <el-row>
                    <el-col :span="6" class="dialog-comData-name">所属业务模块：</el-col>
                    <el-col :span="18" >{{editForm.editNewBlockName}}</el-col>
                </el-row>
            </div>
        </el-dialog>


        <!--添加dialog框-->
        <el-dialog @close="handleDialogClose" title="添加" :visible.sync="importVisible" class="module-dialog" >
            <div class="module-opera" >
                <el-form :model="searchForm" :rules="rules" ref="departmentAdd" label-width="120px" >
                    <el-form-item prop="departmentName" label="部门名称：">
                        <el-input v-model.trim="searchForm.departmentName" class="input-style1"></el-input>
                    </el-form-item>
                    <el-form-item label="上级部门：">
                        <el-input v-model="searchForm.parentName" icon="caret-bottom" placeholder="请选择" class="input-style1"></el-input>
                        <div @click.stop="searchForm.showTree=!searchForm.showTree"
                             style="position: absolute;top:3px;left:0;z-index: 11;width: 100%;max-width:300px;height: 30px;">
                            <div v-show="searchForm.showTree"  class="department-tree-select">
                                <el-tree
                                        :data="treeList"
                                        :props="defaultProps"
                                        show-checkbox
                                        node-key="id"
                                        ref="searchTree"
                                        check-strictly
                                        accordion
                                        highlight-current
                                        @check-change = "selectChange">
                                </el-tree>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item prop="departmentDes" label="描述信息：">
                        <el-input v-model.trim="searchForm.departmentDes"  class="input-style1"></el-input>
                    </el-form-item>
                    <el-form-item label="所属业务模块：">
                        <el-select v-model="value" placeholder="请选择" @change="changeBlockVal"  class="input-style1">
                            <el-option
                                    v-for="item in blockQuote"
                                    :label="item.value"
                                    :value="item.key"
                                    :key="item.key">
                            </el-option>
                        </el-select>

                    </el-form-item>
                    <div class="bottom-btn">
                        <el-button @click="SubmitAddMoudle()" type="primary" icon="el-icon-upload2" size="small">保存</el-button>
                        <el-button @click="importVisible = false" type="warning" icon="el-icon-close"  size="small">取消</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>


        <!--编辑的dialog框-->
        <el-dialog @close="handleDialogClose" title="编辑" :visible.sync="editVisible" class="module-dialog" >
            <div class="module-opera" >
                <el-form :model="editForm" :rules="rules" ref="user-filter" label-width="120px">
                    <el-form-item prop="editCompany" label="部门名称：">
                        <el-input v-model.trim="editForm.editValue"  class="input-style1"></el-input>
                    </el-form-item>
                    <el-form-item label="上级ID" v-show="editForm.editParentId!==0">
                        <el-input v-model="parentName.parentName" icon="caret-bottom" placeholder="请选择" class="input-style1"></el-input>
                        <div @click.stop="editForm.showTree=!editForm.showTree"
                             style="position: absolute;top:3px;left:0;z-index: 11;width: 100%;height: 30px;">
                            <div v-show="editForm.showTree" class="department-tree-select">
                                <el-tree
                                        :data="treeList"
                                        :props="defaultProps"
                                        show-checkbox
                                        accordion
                                        check-strictly
                                        node-key="id"
                                        ref="editTree"
                                        highlight-current
                                        @check-change = "selectEditChange">
                                </el-tree>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item  label="管理者：">
                        <el-autocomplete
                                class="inline-input input-style1"
                                icon="el-icon-search"
                                custom-item="my-item-zh"
                                v-model="leaderNewValue"
                                :fetch-suggestions="queryLeaderSearch"
                                :placeholder="leaderNewValue"
                                :trigger-on-focus="false"
                                @select="handleLeaderSelect"
                        >
                        </el-autocomplete>
                        <!-- <el-select v-model="leaderNewValue" filterable placeholder="请选择" @change="changeLeaderName"  class="input-style1">
                            <el-option
                                    v-for="item in optionNewLeaderNum"
                                    :label="item.name"
                                    :value="item.id"
                                    :key="item.id">
                            </el-option>
                        </el-select> -->
                    </el-form-item>
                    <el-form-item prop="editDes" label="描述信息：" id="desEdit">
                        <el-input  v-model.trim="editForm.editDes"  class="input-style1"></el-input>
                    </el-form-item>
                    <el-form-item label="所属业务模块">
                        <el-select v-model="value2"  @change="changeEditBlockVal"  class="input-style1">
                            <el-option
                                    v-for="item in editBlockQuote"
                                    :label="item.value"
                                    :value="item.key"
                                    :key="item.key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <div class="bottom-btn">
                        <el-button @click="SubmiteditMoudle()" type="primary" icon="el-icon-upload2"  size="small">保存</el-button>
                        <el-button @click="editVisible = false" type="warning" icon="el-icon-close"  size="small">取消</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import Vue from 'vue'
    import {mapGetters} from 'vuex';
    import * as types from '../../store/mutation-types/power-setting/index'
    import axios from '~/plugins/axios';
    import { Row, Col, Form, FormItem, Input, ButtonGroup, Button, Table, TableColumn,Pagination,Dialog,Tag,Tooltip,Tree,Collapse,CollapseItem,Select,cascader,Autocomplete} from 'element-ui'
    import { Icon,MessageBox,Message,Checkbox,Option} from 'element-ui'
    import {setToken, getCookie} from '../../utils/auth'
    
    import { ACTIVEINDEX } from '../../store/mutation-types/left-menu/index'
    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Input);
    Vue.use(Button);
    Vue.use(Table);
    Vue.use(TableColumn);
    Vue.use(Pagination);
    Vue.use(Icon);
    Vue.use(Dialog);
    Vue.use(Tag);
    Vue.use(Tooltip);
    Vue.use(Tree);
    Vue.use(Collapse);
    Vue.use(CollapseItem);
    Vue.use(Select);
    Vue.use(cascader);
    Vue.use(Checkbox);
    Vue.use(Option);
    Vue.use(Autocomplete);
    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;


    Vue.component('my-item-zh', {
        functional: true,
        render: function (h, ctx) {
          var item = ctx.props.item;
          return h('li', ctx.data, [
            h('div', { attrs: { style: 'name' } }, [
                    h('span', { attrs: { style: 'display:inline-block;font-size:12px;' } }, [item.name]),
                    h('span', { attrs: { style: 'display:inline-block;float:right;color: #b4b4b4;;font-size:10px;' } }, [item.position||'无']),
                ]),
            
          ]);
        },
        props: {
          item: { type: Object, required: true }
        }
      });

    export default {
        head(){
            return {
                title: "部门管理"
            }
        },
        data() {
            return {
                tabName: '部门管理',
            	array:[],
                defaultData:[{
                    label: '部门名称'},
                ],
                treeList: [],
                defaultProps: {
                    children: 'childs',
                    label: 'name'
                },
                options: [],
                count: 1,
                checked: true,
                editForm:{
                    editValue:'',
                    editDes:'',
                    parentName:'',
                    editId:'',
                    editBusinessBlock:'',
                    editParentId:'',
                    editNewBlockName:'',
                    leaderName:'',
                    showTree:false,
                    showNewTree:false
                },
                searchForm:{
                    account: "",
                    department: null,
                    departmentName:'',
                    departmentDes:'',
                    departmentBusinessBlock:'',
                    parentName:'',
                    showTree: false,
                    showNewTree : false,
                    role: null,
                    status: null
                },
                positionForm:{
                    department: '',
                    role:''
                },
                rules:{
                    editValue: [
                        { required: true, message: '请输入部门名称', trigger: 'blur' }
                    ],
                    editDes: [
                        { required: false, message: '请输入描述信息', trigger: 'blur' }
                    ]
                },
                rules:{
                    departmentName: [
                        { required: true, message: '请输入部门名称', trigger: 'blur' }
                    ],
                    departmentDes: [
                        { required: false, message: '请输入描述信息', trigger: 'blur' }
                    ]
                },
                blockQuote:[],//所属业务模块
                blockForm:{
                    BusinessBlock : '',
                },//业务模块表单
                editBlockQuote:[],//编辑所属业务模块
                parentName:{
                    parentName : '',
                },
                editVisible : false,
                importVisible : false,
                detailVisible : false,
                value : '',
                value2 : '',
                leaderValue : '',
                leaderNewValue : '',
                leaderInput : '',
                roleName : '',
                optionLeaderNum: [],
                optionNewLeaderNum: [],
            }
        },
        computed: {
            ...mapGetters({
                'pageTabsList': 'getPageTabsList'
            })
        },
        methods: {
        	// 节点被电击的回调
        	nodeclick(data,nodes){
        		this.array=[nodes.level,data.childNum];
        		let Arrays=this.array;
        		 setToken('Arrays',JSON.stringify(this.array));
        	},
            queryLeaderSearch(queryString, cb){
                if(queryString != "" && queryString != " "){
                    var params = {name: queryString}
                    this.getLeaderJson(params).then((res)=>{
                        if(res.data && res.data.data){
                            let list = res.data.data.list;
                            list.forEach((n,i)=>{
                                n.value = n.name
                            });
                            cb(list);
                        }
                    })
                }
            },
            handleLeaderSelect(item){
                this.editForm.leaderName = item.id;
            },
            reFresh(){
                this.treeList = [];
                this.getTreeData();

            },
            handleDialogClose(){
                this.departmentAdd = { departmentValue:'', departmentDes:''};
                this.importVisible = false;
                this.editVisible = false;
            },
            SubmitAddMoudle(){
                this.$refs['departmentAdd'] && this.$refs['departmentAdd'].validate((valid) => {
                    if (valid) {
                        this.addDepartmentInsert();
                    } else {
                        return false;
                    }
                })
            },
            SubmiteditMoudle(node){
                let shuzu=getCookie('Arrays');
                this.array = shuzu? [JSON.parse(shuzu[1]),JSON.parse(shuzu[3])] : [];
				this.upDateDepartment(node);
            },
            addDepartment(){
                this.importVisible = true
                this.getDicttypeDate().then((response)=>{
                    if(response.data && response.data.data){
                        var data = response.data.data;
                        this.blockQuote = data;
                    }
                    
                });
                var memberList = {pageSize:100000000,departmentId: this.editForm.editId}
                this.getLeaderJson(memberList).then((response)=>{
                    if(response.data && response.data.data){
                        var data=response.data.data
                        this.optionLeaderNum = data.list;
                    }
                    
                })
            },
            editDepartment(store,data,node,event){
                this.editVisible = true;
                this.editForm.editId = data.id;
                this.editForm.editValue = data.name;
                this.editForm.editParentId = data.parentId;
                this.editForm.editDes = data.description;
                this.editForm.editBusinessBlock = data.businessBlock;
                this.editForm.editNewBlockName =data.businuessName;
                this.editForm.leaderName =data.leaderId;
                this.leaderNewValue = data.leaderName;
                this.value2 = data.businessBlock;
                this.getDicttypeDate().then((response)=>{
                    if(response.data && response.data.data){
                        var data = response.data.data;
                        this.editBlockQuote = data;
                    }
                    
                });
                this.getDepartmentQuery(data.parentId).then((response)=>{
                    if(response.data && response.data.data){
                        var data = response.data.data;
                        this.parentName.parentName = data.name;
                    }
                });
                var memberList = {pageSize:100000000,departmentId: this.editForm.editId}
                this.getLeaderJson(memberList).then((response)=>{
                    if(response.data && response.data.data){
                        var data=response.data.data
                        this.optionNewLeaderNum = data.list;
                    }
                    
                });
                this.getRoleName(data.leaderId).then((response)=>{

                });

                event.stopPropagation();
            },
            showDetail(store,data,node,event){
                event.stopPropagation();
                this.editForm.editId = data.id;
                this.editForm.editValue = data.name;
                this.editForm.editParentId = data.parentId;
                this.editForm.editDes = data.description;
                this.editForm.editBusinessBlock = data.businessBlock;
                this.editForm.editNewBlockName =data.businuessName;
                this.editForm.leaderName =data.leaderName;
                this.detailVisible = true;
                this.leaderNewValue = data.leaderName;
                this.value2 = data.businessBlock;
                this.getDicttypeDate().then((response)=>{
                    if(response.data && response.data.data){
                        var data = response.data.data;
                        this.editBlockQuote = data;
                    }
                    
                });
                this.getDepartmentQuery(data.parentId).then((response)=>{
                    if(response.data && response.data.data){
                        var data = response.data.data;
                        this.parentName.parentName = data.name;
                    }
                    

                });

            },
            remove(store,data,node,event){
                event.stopPropagation();
                this.$confirm('确定要删除删除部门：'+data.name+'吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.delDepartment(node,data.id);
                }).catch(() => {});
            },
            renderOldContent(h, { node, data, store }) {
                return (
                        <div style="width:100%">
                    <span>
                      <span>{node.label}</span>
                    </span>
                    <span style="float: right; margin-right: 80px">
                        操作
                    </span>
                    <span style="float:right;display:inline-block;margin-right:16%">
                       <el-col style="text-align:center">管理者</el-col>
                    </span>
                    <span style="float:right;margin-right:25%">
                       <el-col type="flex">描述</el-col>
                    </span>
                  </div>);
            },
            renderContent(h, { node, data, store }) {
            
                if(!data.leaderName){
                    data.leaderName = "无"
                    
                }
                return (
                        <div style="width:100%">
                            <span>
                              <span>{node.label}</span>
                            </span>
                            <span style="float: right; margin-right: 5px">
                              <el-button  size="mini"  on-click={ () => this.showDetail(store, data,node,event) } type="primary" icon="el-icon-info" style="padding: 4px 10px">详情</el-button>
                              <el-button  size="mini"  on-click={ () => this.editDepartment(store, data,node,event) } type="primary" icon="el-icon-edit" style="padding: 4px 10px">编辑</el-button>
                              <el-button  size="mini"  on-click={ () => this.remove(store, data,node,event) } type="danger" icon="el-icon-delete" style="padding: 4px 10px">删除</el-button>
                            </span>
                            <span style="float:right;display:inline-block;margin-right:8%;width:10%">
                               <el-col type="flex" style="text-align:center;width:100%">{data.leaderName}</el-col>
                            </span>
                            <span style="float:right;margin-right:20%">
                               <el-col type="flex"style="text-align:center;width:20%" >{data.description}</el-col>
                            </span>
                  </div>);
            },
            getJson(id){
                return axios.get(process.env.baseUrl + "/department/list", {params:{parentId:id
                }})
            },
            getDicttypeDate(){
                return axios.get(process.env.baseUrl + "/dicttype/list", {params:{typeId:115
                }})
            },
            getDepartmentQuery(id){
                return axios.get(process.env.baseUrl + "/department/query", {params:{id:id
                }})
            },
            getLeaderJson(preload){
                return axios.get(process.env.baseUrl + "/member/list", {params:preload})
            },
            getRoleName(id){
                return axios.get(process.env.baseUrl + "/departmentrole/query",{params:{id:id}})
            },
            delDepartment (node,id) {
                var _this = this;
                axios.get(process.env.baseUrl+'/department/delete',{params:{id:id}}).then(function(response){
                    if(!response){
                        return;
                    }
                    if(response.data.code === 0 ){
                        node.parent.removeChild(node);
                        _this.$message({ type: 'success', message: '删除成功'});
                    }else {
                        _this.$message({ type: 'success', message: '删除失败'});
                    }
                })
            },
            addDepartmentInsert(){
                var _this = this;
                var depName = this.searchForm.departmentName;
                var depDes = this.searchForm.departmentDes;
                var depId = this.searchForm.department;
                var BusNum = this.blockQuote.BusinessBlock;
                var leaderId = this.leaderValue;
                if(!depId) {
                    depId = 0;
                }
                axios.post(process.env.baseUrl+'/department/insert',{DeptId:"",Name:depName,ParentId:depId,Description:depDes,LeaderId:leaderId,DingdingId:"",BusinessBlock:BusNum}).then(function(response){
                    if(!response){return}
                    if(response.data.code === 0 ){
                        _this.importVisible =  false;
                        _this.searchForm = {
                            account: "",
                            department: null,
                            departmentName:'',
                            departmentDes:'',
                            parentName:'',
                            departmentBusinessBlock:'',
                            showTree: false,
                            showNewTree : false,
                            role: null,
                            status: null
                        };
                        _this.blockQuote = [];
                        _this.$message({ type: 'success', message: '添加成功'});
                        setTimeout(()=>{
                            window.location.reload();
                        },100);

                    }else {
                        _this.$message({ type: 'warning', message: '添加失败'});
                    }
                })
            },

            //递归遍历Tree
            extendTree(data,treeId){
                data.forEach((n)=>{
                    if(n.id == treeId){
                        n.name = this.editForm.editValue;
                        n.description = this.editForm.editDes;
                        n.businessBlock = this.editForm.editBusinessBlock;
                        n.leaderId = this.editForm.leaderName;
                        n.leaderName = this.leaderNewValue;
                    }else if(n.childs){
                        this.extendTree(n.childs,treeId)
                    }
                })
            },

            upDateDepartment(){

                var _this = this;

                var editId = this.editForm.editId;
                var depName = this.editForm.editValue;
                var depDes = this.editForm.editDes;
                var edParentId = this.editForm.editParentId;
                var edBus = this.editForm.editBusinessBlock;
                var leaderId = this.leaderNewValue?this.editForm.leaderName:"";
                axios.post(process.env.baseUrl+'/department/update',{id:editId,DeptId:"",Name:depName,ParentId:edParentId,Description:depDes,LeaderId:leaderId,DingdingId:'',BusinessBlock:edBus}).then(function(response){
                    if(response.data.code === 0 ){
                        _this.editVisible =    false;
                        _this.$message({ type: 'success', message: '编辑成功'});
                        _this.extendTree(_this.treeList,editId);

//                      setTimeout(()=>{
//                          window.location.reload();
//                      },100)  
//						解决bug ：部门管理 保存后定位至原展开形式  把settimeout  去掉
						

                    }else {
                        _this.$message({ type: 'warning', message: '编辑失败'});
                    }
                })
            },
            selectChange(data,checked){
                if(checked) {
                    this.searchForm.department = data.id;
                    this.searchForm.parentName = data.name;
                    this.searchForm.showTree = !this.searchForm.showTree;
                    this.$refs.searchTree.setCheckedKeys([]);
                    this.$refs.searchTree.setChecked(data,true)
                }

            },
            selectOtherChange(data,checked){
                if(checked){
                    this.searchForm.departmentBusinessBlock = data.businessBlock;
                    this.searchForm.showNewTree = !this.searchForm.showNewTree
                    this.$refs.searchNewTree.setCheckedKeys([])
                    this.$refs.searchNewTree.setChecked(data,true)
                }
            },
            selectEditChange(data,checked){
                if(checked) {
                    this.editForm.editParentId = data.id;
                    this.parentName.parentName = data.name;
                    this.editForm.showTree = !this.editForm.showTree;
                    this.$refs.editTree.setCheckedKeys([]);
                    this.$refs.editTree.setChecked(data,true)
                }
            },
            selectEditOtherChange(data,checked){
                if(checked) {
                    this.editForm.editBusinessBlock = data.businessBlock;
                    this.editForm.showNewTree = !this.editForm.showNewTree;
                    this.$refs.editNewTree.setCheckedKeys([]);
                    this.$refs.editNewTree.setChecked(data,true)
                }
            },
            changeBlockVal(data){
                this.blockQuote.BusinessBlock = data;
            },
            changeEditBlockVal(data){
                this.value2 = data;
                this.editForm.editBusinessBlock = data;
            },
            hideDialog(){
                this.searchForm.showTree = false;
                this.searchForm.showNewTree = false;
                this.editForm.showTree = false;
                this.editForm.showNewTree=false;
            },
            // changeLeaderName(value){
            //     this.editForm.leaderName = value;
            // },
            getTreeData() {
                this.$store.dispatch('getTreeList')
                    .then((response) => {
                        var result = response.data;
                        if(result && result.data){
                            this.treeList.push(result.data)
                        }
                    })
            }
        },
        created(){
            this.getTreeData();
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
    .bottom-btn{
        width:100%;
        display:table;
        text-align:center;
    }
    #dep-tree{
        min-height: 520px;
    }
    .el_tree1{
        border-bottom: none;
        border-top: none;
        background:#e4e8f1;
    }
    .el-row {
        margin-bottom: 20px;
    &:last-child {
         margin-bottom: 0;
     }
    }
    .el-col {
        border-radius: 4px;
    }
    .bg-purple-dark {
        background: #99a9bf;
    }
    .bg-purple {
        background: #d3dce6;
        text-align:center;
        color:#fff;
        line-height:36px;
    }
    .bg-purple-light {
        background: #e5e9f2;
    }
    .grid-content {
        border-radius: 4px;
        min-height: 36px;
    }
    .row-bg {
        padding: 10px 0;
        background-color: #f9fafc;
    }
    .el-tree-node__content span:nth-of-type(2){
        margin-right:100px;
    }

    .dialog-company-detail{
        border-top:1px solid #dfe6ec;
        border-left:1px solid #dfe6ec;
        background-color: #f1f2f2;
    .el-row{
        border-bottom:1px solid #dfe6ec;
        border-right:1px solid #dfe6ec;
        line-height: 24px;
        margin-bottom: 0px;
    }
    .el-col{
        min-height: 24px;
        padding: 0 8px;
    }
    .dialog-comData-name{
        padding-right: 4px;
        text-align: right;

    & + div{
            border-left:1px solid #dfe6ec;
            background-color: #fff;
            text-indent:10px;
        }
    }
    }
    .fixElCol .el-icon-caret-top:before{
        content : ''!important;
    }
    .top-edit{
        padding: 10px 10px;
        text-align: left;
        border:1px solid #DFE6EC;
    }
    .top-edit button{
        margin:0 10px;
    }
    .input-style1{
        width: 200px;
    }
    .input-style2{
        width: 100%;
    }

</style>